package com.example.javafx.bilibilidownload.util;

import com.example.javafx.bilibilidownload.constant.JsoupConstant;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.HashMap;
import java.util.Map;

public class JsoupUtils {

    private static final Logger log = LogManager.getLogger(JsoupUtils.class);


    private static boolean useProxy = false;

    private static int timeout = 15000;

    private static int count = 0;

    public static String getStringDoc(String url, Map header) {
        return (String) getDoc(url, JsoupConstant.STRING, header);
    }

    public static JsonNode getJsonNodeDoc(String url, Map header) {
        return (JsonNode) getDoc(url, JsoupConstant.JSONNODE, header);
    }

    public static Document getDoc(String url, Map header) {
        return (Document) getDoc(url, JsoupConstant.DOC, header);
    }

    public static Object getDoc(String url, String type, Map header) {
        String resultStr = "";
        if (null == header) {
            header = new HashMap();
        }
        Connection.Response response;
        try {
            Connection connection = Jsoup.connect(url).headers(header).ignoreContentType(true).timeout(timeout);
            response = connection.execute();
            if (null != response && response.statusCode() == 429) {
                Thread.sleep(5000);
            }
            if (null != response && response.statusCode() == 412) {
                Thread.sleep(5000);
            }
            if (null != response && response.statusCode() == 200) {
                Thread.sleep(1000);
                resultStr = response.body();
            }
        } catch (Exception e) {
            log.error("getdoc报错, 错误信息是:{}, 请求url是:{}", e, url);
        }
        if (StringUtils.isEmpty(resultStr)) {
            log.info("没有获取到内容, 请求url是: {}", url);
            return null;
        }
        if (StringUtils.isEmpty(type)) {
            type = JsoupConstant.STRING;
        }
        //各种返回类型
        if (JsoupConstant.STRING.equals(type)) {
            return resultStr;
        }
        if (JsoupConstant.JSONNODE.equals(type)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.readTree(resultStr);
            } catch (JsonProcessingException e) {
                log.error("getDoc返回jsonnode失败, 请求url是：{}, 异常信息是: {}", url, e.getMessage());
            }
        }
        if (JsoupConstant.DOC.equals(type)) {
            return Jsoup.parse(resultStr);
        }
        return null;
    }
}
